//
//  StatusPictureView.swift
//  TYHWeibo
//
//  Created by IOS on 15/8/6.
//  Copyright © 2015年 IOS. All rights reserved.
//

import UIKit
import SDWebImage

///选中照片的通知
let TYHStatusCellSelectPictureNotification = "TYHStatusCellSelectPictureNotification"
///URL 的key
let TYHStatusCellSelectPictureURLKey = "TYHStatusCellSelectPictureURLKey"
///indexPath key
let TYHStatusCellSelectPictureIndexPathKey = "TYHStatusCellSelectPictureIndexPathKey"


class StatusPictureView: UICollectionView {

    var status: Status? {
        didSet {
            sizeToFit()
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
       return calcViewSize()
    }
    
    //计算视图大小
    private func calcViewSize() -> CGSize {
        //准备常量
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10
        //每行最多显示图片数
        let rowCount = 3
        
        pictureViewLayout.itemSize = itemSize
        //根据图片数计算试图打消
        let count = status?.pictureURLs?.count ?? 0
        // 1. 没有图片
        if count == 0 {
            return CGSizeZero
        }
        
        // 2. 1张图片
        if count == 1 {
//            let size = CGSize(width: 150, height: 120)
            //从 SDWebImage 中获取缓存图片的大小
            // key 是下载图片 url 的完整字符串
            let key = status?.pictureURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            var size = CGSize(width: 150, height: 120)
            
            if image != nil {
                size = image.size
            }
            
            //对图片尺寸进一步判断,防止过宽过窄
            size.width = size.width > UIScreen.mainScreen().bounds.width ? 150 : size.width
            size.width = size.width < 40 ? 40 : size.width
            
            
            pictureViewLayout.itemSize = size
            
            return size
        }
        
        //3. 4张图片
        if count == 4 {
            let w = itemSize.width * 2 + margin
            return CGSize(width: w, height: w)
        }
        
        //4. 其他
        // 计算行数
        let row = (count - 1) / rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + margin * CGFloat(rowCount - 1)
        let h = itemSize.height * CGFloat(row) + margin * CGFloat(row - 1)
        return CGSize(width: w, height: h)
    }
    
    //布局
    private let pictureViewLayout = UICollectionViewFlowLayout()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: pictureViewLayout)
        backgroundColor = UIColor.lightGrayColor()
        
        //注册可充用cell
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: "statusPictureViewCellID")
        
        self.dataSource = self
        self.delegate = self
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
   
    

}

// 在 swift 中，协议同样可以通过 extension 来写，可以将一组协议方法，放置在一起，便于代码维护和阅读！
extension StatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //发送通知
//        print(status?.largePictureURLs)
        NSNotificationCenter.defaultCenter().postNotificationName(TYHStatusCellSelectPictureNotification, object: self, userInfo:
            [TYHStatusCellSelectPictureURLKey: status!.largePictureURLs!, TYHStatusCellSelectPictureIndexPathKey: indexPath])
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("statusPictureViewCellID", forIndexPath: indexPath) as! StatusPictureViewCell
        cell.imageURL = status!.pictureURLs![indexPath.item]
        return cell
    }
    
    
}

class StatusPictureViewCell: UICollectionViewCell {
   
    var imageURL: NSURL? {
        didSet {
           iconview.sd_setImageWithURL(imageURL!)
            
            gifImageView.hidden = ((imageURL!.absoluteString as NSString).pathExtension.lowercaseString != "gif")
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(iconview)
        iconview.addSubview(gifImageView)
        gifImageView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: iconview, size: nil)
        iconview.ff_Fill(contentView)
    }
    
    private lazy var iconview: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        return iv
    }()
    
    //GIF图片
    private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
}



